import { deviceSetting } from "@/api";
import { asyncExecFunction } from "@/king-components/js/KingonPlus";
import { getDeviceSerialNumber } from "@/utils/util";
import dayjs from "dayjs";
import { signFaceModule } from "../faceUpdate";

/**
 * 百度人脸SDK 应用层使用流程
 *
 *  使用激活码激活设备 -> 初始化SDK > 可以进行人脸识别/注册人脸等SDK API操作
 *
 *   * 1. 激活设备只需要激活一次，永久有效（除非设备指纹变了，关于这个情况官方文档有说明）
 *   * 2. 初始化SDK，每次启动应用都需要初始化一次
 */

/**
 * 人脸识别本地缓存数据
 */
const face = {
  /** 命名空间 - actions内调用不需要加空间名 face. 其他需要，如 commit('face/setHardwareFingerprint') */
  namespaced: true,
  state: {
    // 设备指纹
    hardwareFingerprint: uni.getStorageSync("__DEVICE__hardwareFingerprint") || "",
    // 设备激活码(人脸)
    activationCode: uni.getStorageSync("__DEVICE__activationCode") || "",
    // 是否已激活
    isActivated: uni.getStorageSync("__DEVICE__isActivated") || false,
    // SDK 初始化状态
    isSDKInit: uni.getStorageSync("__DEVICE__isSDKInit") || false,
    // 定时器 （因为修改了初始化时机，可能会导致多次进行拉取，避免定时器被多次调用）
    timerCode: uni.getStorageSync("__DEVICE__timerCode") || "",
    // 本地人脸数据（文件路径列表）
    //  localFaceData: uni.getStorageSync("__APP__localFaceData") || [],
    // 本地人脸数据最后更新时间
    //  localFaceDataLastUpdateTime: uni.getStorageSync("__APP__localFaceDataLastUpdateTime") || 0,
  },
  getters: {
    getHardwareFingerprint: async (state: any) => {
      return state.hardwareFingerprint || "-";
    },
    getActivationCode: (state: any) => {
      return state.activationCode;
    },
    isActivated: (state: any) => {
      return state.isActivated;
    },
    getTimeCode: (state: any) => {
      return state.timerCode;
    },
    isSDKInit: (state: any) => {
      return state.isSDKInit;
    }
  },
  actions: {
    // 初始化硬件指纹 (这个不是初始化人脸功能的流程， 只当作查询唯一id的一个方式🤔)
    async initHardwareFingerprint({ commit, state }: any) {
      // 获取硬件指纹
      try {
        const fingerprint = await asyncExecFunction("baiduGetHardwareFingerprint");
        if (!fingerprint) throw new Error("获取不到硬件指纹");
        console.log("[initFaceModule ] 获取硬件指纹", fingerprint);
        commit("setHardwareFingerprint", fingerprint);
      } catch (error) {
        console.error("[initFaceModule ] 人脸模块获取硬件指纹失败 init", error);
        uni.showToast({
          title: "获取硬件指纹失败",
          icon: "none",
          duration: 1000,
          position: "bottom",
        });
        // 重新抛出异常
        throw error;
      }
    },
    // 初始化人脸设备激活码 并进行激活
    async initActivationCode({ commit, state }: any, paylod: any = {}) {
      // 获取设备激活码, 如果已经有激活码了就不要再获取(除非强制获取)
      try {
        if (!state.activationCode || paylod?.force === true) {
          const deviceCode = await getDeviceSerialNumber();
          try {
            const { data } = await deviceSetting(deviceCode);
            if (data?.settingValue) {
              commit("setActivationCode", data.settingValue);
            } else {
              throw {
                messag: "接口未返回激活码配置数据",
                errorKey: "#1",
              };
            }
          } catch (error) {
            // 抛出异常
            throw new Error("接口未返回激活码配置数据");
          }
        }

        console.log("[initActivationCode ] 激活百度人脸识别 -> activationCode:", state.activationCode);
        // 在线激活
        await asyncExecFunction("baiduOnlineActivation", state.activationCode);
        // 激活成功设置
        commit("setIsActivated", true);
      } catch (error: any) {
        console.error("[initActivationCode ] 人脸模块获取设备激活码失败 init", error.toString());

        let errorKey = "";
        if (error.errorKey && error.errorKey == "#1") {
          errorKey = "#1 无法获取激活码";
        } else if (error.toString()?.includes("has actived on other device")) {
          errorKey = "#2 激活码已绑定其他设备";
        } else {
          errorKey = "#3";
        }

        // 如果存在激活码，则删除激活码
        if (state.activationCode) {
          commit("setActivationCode", "");
        }

        uni.showToast({
          title: "设备人脸激活失败" + errorKey,
          icon: "none",
          duration: 1000,
          position: "bottom",
        });
        // uni.showModal({
        //   title: "人脸模块",
        //   content: "设备人脸激活失败",
        // });
        // 重新抛出异常
        throw error;
      }
    },
    // 初始化人脸SDK
    async initFaceSDK({ commit, state }: any) {
      try {
        // 初始化人脸模块
        await asyncExecFunction("baiduInitialization");
      
        commit("setIsSDKInit", true);
      } catch (error) {
        commit("setIsSDKInit", false);
        console.error("[initFaceModule ] 人脸SDK初始化失败", error.toString());
        uni.showToast({
          title: "人脸SDK初始化失败",
          icon: "none",
          duration: 1000,
          position: "bottom",
        });
        // uni.showModal({
        //   title: "人脸模块",
        //   content: "硬件激活/初始化失败",
        // });
        // 重新抛出异常
        throw error;
      }
    },
    // 启动定时器定时拉取人脸数据 （需在激活且初始化完成之后使用）
    async startFaceTimer({ commit, state }: any) {
      if (state.timerCode) {
        clearTimeout(state.timerCode);
        state.timerCode = null;
      }
      state.timerCode = setTimeout(async () => {
        await signFaceModule();
        clearTimeout(state.timerCode);
        state.timerCode = null;
        uni.setStorageSync("__DEVICE__timerCode", state.timerCode);
        /** 这里设置 5s 因为初始化完成后不能立即注册人脸  */
      }, 5000);
      uni.setStorageSync("__DEVICE__timerCode", state.timerCode);
    },
  },
  mutations: {
    // 设置硬件指纹
    setHardwareFingerprint(state: any, hardwareFingerprint: any) {
      state.hardwareFingerprint = hardwareFingerprint;
      uni.setStorageSync("__DEVICE__hardwareFingerprint", hardwareFingerprint);
    },
    // 设置激活码
    setActivationCode(state: any, activationCode: any) {
      console.log("保存激活码 -> activationCode:", activationCode);
      try {
        state.activationCode = activationCode;
        uni.setStorageSync("__DEVICE__activationCode", activationCode);
      } catch (error) {
        console.error("设置激活码失败", error.toString());
      }
    },
    // 设置是否激活
    setIsActivated(state: any, isActivated: any) {
      state.isActivated = isActivated;
      uni.setStorageSync("__DEVICE__isActivated", isActivated);
    },
    // 设置定时器ID
    setTimerCode(state: any, timerCode: any) {
      state.timerCode = timerCode;
      uni.setStorageSync("__DEVICE__timerCode", timerCode);
    },
    // 设置是否初始化
    setIsSDKInit(state: any, isSDKInit: any) {
      state.isSDKInit = isSDKInit;
      uni.setStorageSync("__DEVICE__isSDKInit", isSDKInit);
    },
    clear(state: any) {
      // 清除数据
      const clearKeys = Object.keys(state);
      clearKeys.forEach((key) => {
        const keyName = "__DEVICE__" + key;
        state[keyName] = {};
        uni.removeStorageSync(keyName);
      });
    },
    /** 设置本地人脸数据 */
    // setLocalFaceData(state: any, data: any) {
    //   if (!data || !Array.isArray(data)) return console.error("setLocalFaceData 参数错误");
    //   const now = new Date().getTime();
    //   state.localFaceData = data;
    //   state.localFaceDataLastUpdateTime = now;
    //   uni.setStorageSync("__APP__localFaceData", data);
    //   uni.setStorageSync("__APP__localFaceDataLastUpdateTime", now);
    // },
  },
};
export default face;
